/**
 * 
 */
package com.ly.mpayment.core.util;

import java.io.ByteArrayOutputStream;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFCellUtil;

/**
 * @项目 backend-web
 * @时间 2014年3月14日 下午5:49:24
 * @版本 1.0.0
 * @描述 无格式导出父类
 */
public abstract class ExcelFileWrite<T> {

	private HSSFWorkbook workBook;
	private List<T> dataSource;
	private String sheetNamea;
	
	public ExcelFileWrite(List<T> dataSource , String sheetName) {
		this.dataSource = dataSource;
		this.sheetNamea = sheetName;
		workBook = new HSSFWorkbook();
	}
	
	
	/**
	 * 写数据
	 * @return
	 * @throws Exception
	 */
	public byte[]  writeFile() throws Exception{
			pushData();
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			workBook.write(outputStream);
			return outputStream.toByteArray();
	}
	
	/**
	 * 构造数据
	 */
	private void pushData(){
		HSSFSheet sheet =  workBook.createSheet(sheetNamea);
		sheetHeader(sheet, getHeader());
		setSheetData(dataSource, sheet);
	}
	
	/**
	 * 给文本创建sheet头
	 * @param sheet
	 * @param header
	 */
	private  void sheetHeader(HSSFSheet sheet ,String[] header){
		HSSFRow headerRow = sheet.createRow(0);
		for(int i=0 ; i<header.length; i++){
			HSSFCellUtil.createCell(headerRow, i, header[i]);
		}
	}
	
	/**
	 * 设置文件的数据
	 * @param dataSource
	 * @param sheet
	 */
	private  void setSheetData(List<T> dataSource,HSSFSheet sheet){
		int index = 1;
		int sheetName=1;
		for(int i=0;i<dataSource.size();i++){
			Object[] dataArray = getRow(index, dataSource.get(i));
			//判断是不是到达sheet页的最大行数，如果是则新开一个sheet
			if((index+1)==65535){
				sheet = workBook.createSheet(sheetNamea+sheetName);
				sheetHeader(sheet, getHeader());
				sheetName++;
				index = 1;
			}
			HSSFRow row = sheet.createRow(index);
			index++;
			for(int j=0;j<dataArray.length;j++){
				HSSFCellUtil.createCell(row, j, dataArray[j] == null ?"":dataArray[j].toString());
			}
		}
	}
	
	
	/**
	 * 获取导出文件的头信息
	 * @return
	 */
	protected abstract  String[] getHeader();
	
	/**
	 * 解析每行数据
	 * @param index
	 * @param t
	 * @return
	 */
	protected abstract Object[] getRow(int index ,T t);
}
